/*
 *  Copyright (c) 1998, Regents of the University of California
 *  All rights reserved.
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *      * Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above copyright
 *        notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 *      * Neither the name of the University of California, Berkeley nor the
 *        names of its contributors may be used to endorse or promote products
 *        derived from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.demis.elf.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.demis.elf.configuration.DatabaseConfiguration;
import org.demis.elf.configuration.SupportedDBMS;

/**
 * @version 1.0
 * @author <a href="mailto:demis27@demis27.net">Stéphane kermabon</a>
 */
public class H2Utils {

    private static final Log logger = LogFactory.getLog(H2Utils.class);

    public static DatabaseConfiguration createDatabase(String projectPath, String scripts) {
        DatabaseConfiguration elfConfiguration = new org.demis.elf.configuration.DatabaseConfiguration();
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName("org.h2.Driver");
            String dbName = "tempdata" + System.currentTimeMillis();
            String url = "jdbc:h2:file:" + System.getProperty("java.io.tmpdir") + File.separator + dbName;

            connection = DriverManager.getConnection(url, "sa", "");
            statement = connection.createStatement();
            for (String scriptFilename : scripts.split(";")) {
                logger.info("read an execute script : " + (new File(scriptFilename)).getAbsoluteFile());
                String script = IOUtils.toString(new FileInputStream(projectPath + File.separator + scriptFilename));
                logger.info("script to execute : " + script);
                statement.execute(script);
            }

            elfConfiguration.setUrl(url);
            elfConfiguration.setDbms(SupportedDBMS.H2);
            elfConfiguration.setPassword("");
            elfConfiguration.setSchemaName("public");
            elfConfiguration.setUser("sa");
            elfConfiguration.setFilter(null);
            elfConfiguration.setReadData(false);
        } catch (ClassNotFoundException ex) {
            logger.error("Error when creating H2 database", ex);
        } catch (SQLException sqle) {
            logger.error("Error when creating H2 database", sqle);
        } catch (IOException ioe) {
            logger.error("Error when creating H2 database", ioe);
        }
        finally {
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException ex) {
                    logger.error("failed to close statement", ex);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException ex) {
                    logger.error("failed to close connection", ex);
                }
            }
        }
        return elfConfiguration;
    }
}
